﻿using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.IO;
using System.Windows.Forms;
using Close2Poco.Tests.TestEntities;

namespace Close2Poco.Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        DataContext _context;

        MappingSource CreateClose2PocoMappingSource()
        {
            return Close2Poco.MappingGenerator.CreateMappingSource();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            DataContext context = new DataContext(textConnectionString.Text, CreateClose2PocoMappingSource());
            using (StringWriter w = new StringWriter())
            {
                context.Log = w;

                // actually create the database
                context.CreateDatabase();

                // and here is the creation script that we used to do it
                // Idea of capturing it is that Script can be re-run (e.g. on a different server)
                // TODO: in current version, you have to manually remove the line that looks like this: .Net SqlClient Data Provider: Changed database context to 'SampleDatabaseCreatedByClose2Poco'..
                textCreationScript.Text = w.ToString();
            }

            LoadData();
        }

        void LoadData()
        {
            dataGridView1.AutoGenerateColumns = true;
            _context = new DataContext(textConnectionString.Text, CreateClose2PocoMappingSource());
            var bindingList = _context.GetTable<Customer>().GetNewBindingList();
            bindingSource1.DataSource = bindingList;
            dataGridView1.Columns.Remove("Orders");  // hide this one in this version of the demo
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            dataGridView1.EndEdit();
            _context.SubmitChanges();
            LoadData();  // start with a fresh context (i.e. implicit reload after save). Not required by Close2Poco, just a pattern that I like
        }



    }
}
